<template>
  <div class="common-layout" style="height: 100%;">
    <el-container>
      <el-main style="background-color: var(--el-color-primary);overflow: hidden;">
        <img src="/images/login/bg1.jpg" style="height: 100%;min-width: 100%;"/>
      </el-main>
      <el-aside width="550px">
        <div class="farm2LoginForm">
          <div class="title">
            <img :src="sysConfig.getLogoPath" alt="Logo" /> {{ sysConfig.getSysTitle }}
          </div>
          <el-form @keydown.enter="handleSubmit" ref="formRef" v-loading="isLoading" :inline="true" :model="form"
            class="demo-form-inline">
            <el-form-item style="width: 100%;" prop="loginname" :rules="v.getRegExpRules(v.ValidRxs.loginname, true)">
              <el-input prefix-icon="User" size="large" v-model="form.loginname" placeholder="登录名" clearable
                :validate-event="false" />
            </el-form-item>
            <el-form-item style="width: 100%;" prop="password" :rules="v.getRules(true)">
              <el-input prefix-icon="Lock" size="large" v-model="form.password" type="password" placeholder="登录密码"
                show-password :validate-event="false" />
            </el-form-item>
            <el-form-item style="width: 100%;" v-if="isShowImgCode" prop="imgcode" :rules="v.getRules(true)">
              <el-input prefix-icon="Picture" show-word-limit v-model="form.imgcode" maxlength="4" type="text"
                style="width: 100%;" placeholder="验证码">
                <template #suffix>
                  <img @click="refreshCaptcha" :src="captchaUrl"
                    style="height: 100%;width: 100px;padding: 2px;cursor: pointer;" alt="Logo" />
                </template>
              </el-input>
            </el-form-item>
            <div style="text-align: right;">
              <el-switch v-model="isSaveLogin" class="mt-2" style="margin-left: 24px" inline-prompt active-icon="Check"
                inactive-icon="Close" /><span style="font-size: 12px;color: #999999;">&nbsp;保持登录</span>
            </div>
            <div style="text-align: center;">
              <el-button style="width: 100%;margin-top:20px  ;" @click="doLogin" size="large"
                type="primary">登录</el-button>
            </div>
          </el-form>
        </div>
      </el-aside>
    </el-container>
  </div>
</template>
<script setup lang="ts">
import { useSystemConfigStore } from '@/store/useSystemConfigStore';
import { useUserInfoStore } from '@/store/useUserInfoStore';
import Farm2Request from '@/service/remoteRequests/Farm2Request';
import { reactive, ref } from 'vue';
import v from '@/hook/farmFormValids';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import type { DataResponse } from '@/types/commons/DataResponse';
import notice from '@/components/msg/FarmNotice';
import { useRouter } from 'vue-router';
import farmPasswordUtils from '@/hook/farmPasswordUtils';

const captchaUrl = ref(Farm2Request.getFullPath(''));
const sysConfig = useSystemConfigStore();
const userInfo = useUserInfoStore();
const isLoading = ref(false);
const isSaveLogin = ref(false);
const isShowImgCode = ref(false);
const router = useRouter();

const formRef = ref()

const form = reactive({
  loginname: '',
  password: '',
  imgcode: '',
});




function refreshCaptcha() {

  if (form.loginname && form.loginname != '') {
    captchaUrl.value = `${Farm2Request.getFullPath('api/login/captcha/' + form.loginname)}?t=${new Date().getTime()}`;
  }
}

const handleSubmit = () => {
  doLogin();
}
let codes = { webcode: { code: "", val: "" }, syscode: "", imgcode: false }

/**
 * 执行登录
 */
const doLogin = async () => {

  await formRef.value.validate((valid: boolean) => {
    if (valid) {

      Farm2Request.submit("api/login/info", RequestTypeEnum.post, isLoading, {
        loginname: form.loginname, password: 'none', code: 'none'
      }).then((dataResponse: DataResponse) => {
        codes = dataResponse.data as { webcode: { code: string, val: string }, syscode: string, imgcode: boolean };
        if (codes.imgcode) {

          isShowImgCode.value = true;

          if (!form.imgcode) {
            refreshCaptcha();
          }
        } else {
          isShowImgCode.value = false;
        }
        formRef.value.validate((revalid: boolean) => {
          if (revalid) {
            {
              farmPasswordUtils.encodeWebPassword(codes.syscode, codes.webcode.val, form.password, (webPassword: string) => {

                Farm2Request.submit("api/login/auth", RequestTypeEnum.post, isLoading,
                  { loginname: form.loginname, password: webPassword, code: codes.webcode.code, imgcode: form.imgcode }
                ).then((dataResponse: DataResponse) => {

                  userInfo.setJwt((dataResponse.data as { token: string }).token,isSaveLogin.value);

                  router.push('/home');
                }).catch((msg: Error) => {
                  notice.byError(msg.message);
                  form.imgcode = '';
                  form.password = '';
                  if (isShowImgCode.value) {
                    refreshCaptcha();
                  }
                });
              });
            }
          }
        });
      }).catch((msg: Error) => {
        notice.byError(msg.message);
      });
    }
  });

}

</script>
<style>
.farm2LoginForm {
  padding: 5rem 8rem;
}

.farm2LoginForm img {
  border-radius: 10px;
  max-height: 32px;
}

.farm2LoginForm .title {
  font-size: 36px;
  padding-top: 50px;
  color: #25396f;
  font-weight: 700;
  margin-bottom: 20px;
}

.farm2LoginForm .el-form-item__error {
  color: #f3616d;
}
</style>
